/*
 * @Author: lihaogn
 * @Date: 2021-06-24 19:38:22
 * @LastEditTime: 2022-01-07 11:00:08
 * @LastEditor: lihaogn
 * @Description: 登录 controller
 * @FilePath: \lix-admin-base-server\app\controller\login.js
 */

const Controller = require("egg").Controller;
const { SuccessResponse, ErrorResponse } = require("../dto/responseDto");

class LoginController extends Controller {
  /**
   * @description: 用户登录
   * @param {*}
   * @return {*}
   */
  async login() {
    const { ctx, app } = this;
    const res = await ctx.service.login.loginCheck(ctx.request.body);

    if (res) {
      // 生成 token
      const token = app.jwt.sign(
        {
          userId: res.user_id,
        },
        app.config.jwt.secret,
        {
          expiresIn: 3600 * 12,
        }
      );

      if (res.id === undefined) {
        ctx.body = new ErrorResponse(null, {
          title: "登录失败",
          content: res.message,
        });
      } else {
        ctx.body = new SuccessResponse(res, "登录成功", token);
      }
    } else {
      ctx.body = new ErrorResponse(null, {
        title: "登录失败",
        content: "用户名或密码错误",
      });
    }
  }
}

module.exports = LoginController;
